import type { Result } from '../util/handler';
import { handleResponse } from "../util/handler";

async function login(params: { username: string; password: string }): Promise<Result<string>> {
  return await fetch('/api/user/login', {
    method: 'post',
    credentials: 'same-origin',
    body: JSON.stringify(params),
    headers: {
      'content-type': 'application/json'
    }
  }).then((resp) => handleResponse<string>(resp));
}

async function logout(token: string): Promise<Result<null>> {
  return await fetch('/api/user/logout', {
    method: 'post',
    credentials: 'same-origin',
    headers: {
      'content-type': 'application/json',
      'token': token
    }
  }).then((resp) => handleResponse<null>(resp));
}

async function register(params: { username: string; password: string }): Promise<Result<null>> {
  return await fetch('/api/user/register', {
    method: 'post',
    credentials: 'same-origin',
    body: JSON.stringify(params),
    headers: {
      'content-type': 'application/json'
    }
  }).then((resp) => handleResponse<null>(resp));
}

async function updatePassword({ originalPassword, newPassword, token }: { originalPassword: string; newPassword: string, token: string }): Promise<Result<null>> {
  return await fetch('/api/user/update', {
    method: 'post',
    credentials: 'same-origin',
    body: JSON.stringify({
      originalPassword,
      newPassword
    }),
    headers: {
      'content-type': 'application/json',
      'token': token
    }
  }).then((resp) => handleResponse<null>(resp));
}

async function changeTypeToSeller(token: string): Promise<Result<null>> {
  return await fetch('/api/user/toSeller', {
    method: 'post',
    credentials: 'same-origin',
    headers: {
      'content-type': 'application/json',
      'token': token
    }
  }).then((resp) => handleResponse<null>(resp));
}

async function queryUserType(token: string): Promise<Result<{ userType: number }>> {
  return await fetch('/api/user/info', {
    method: 'post',
    credentials: 'same-origin',
    headers: {
      'content-type': 'application/json',
      'token': token
    }
  }).then((resp) => handleResponse<{ userType: number }>(resp));
}

export {
  login,
  logout,
  register,

  queryUserType,
  
  updatePassword,
  changeTypeToSeller,
}